//
//  NewOrdorListViewController.m
//  HCNewGoldFinger
//
//  Created by 刘琛 on 2018/3/12.
//  Copyright © 2018年 zjhcsoftios. All rights reserved.
//

#import "NewOrdorListViewController.h"
#import "NewOrdorListCell.h"
#import "ZSBWorkOrderRightMenuView.h"
#import "NewOrdorListModel.h"
#import "NewOrderDetailViewController.h"
#import "NewMissonListDetailController.h"
#import "NewOrdorListDetailViewController.h"
#import "NewMarketWebViewController.h"
#import <MJExtension/MJExtension.h>
#import "iSeeNetworkRequest.h"
#import "NetworkAddress.h"
#import "NSBundle+AssociatedBundle.h"
#import "MJRefresh.h"
#import "UIColor+EX.h"
#import "SVProgressHUD.h"
#import "ISeeUserInfoModel.h"

@interface NewOrdorListViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,UISearchResultsUpdating,NewOrdorListCellDelegate>

@property (nonatomic,retain) UISearchController *searchController;

@property (nonatomic, strong) NSMutableArray <NewOrdorListModel *> *dateList;
@property (nonatomic, copy)NSString *datestr;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSString *searchKey;
//抽屉
@property (nonatomic, strong) ZSBWorkOrderRightMenuView *muneView;
@end

@implementation NewOrdorListViewController

static NSString *newOrdorListCellIdentify = @"newOrdorListCellIdentify";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self muneViewInit];
    
    _tableView.rowHeight = UITableViewAutomaticDimension;
    [_tableView registerNib:[UINib nibWithNibName:@"NewOrdorListCell" bundle:[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"]] forCellReuseIdentifier:newOrdorListCellIdentify];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getNewList];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self getMoreList];
    }];
    
    _dateList = [NSMutableArray array];
    
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    //设置代理
    self.searchController.delegate= self;
    self.searchController.searchResultsUpdater = self;
    //包着搜索框外层的颜色
    self.searchController.searchBar.barTintColor = [UIColor colorWithHexString:@"E6E8EA"];
    //提醒字眼
    self.searchController.searchBar.placeholder= @"请输入关键字搜索";
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    // 添加 searchbar 到 headerview
    self.tableView.tableHeaderView = self.searchController.searchBar;
//    self.definesPresentationContext = YES;
    
    [self getNewList];
    
}

- (void)muneViewInit {
    

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"list"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction:)];
    
    _muneView = [[ZSBWorkOrderRightMenuView alloc] init];
    _muneView.order = YES;
    
    //抽屉接口
    __weak __typeof(self)weakSelf = self;
    _muneView.clickBlock = ^(ZPMenuModel *model){
        weakSelf.datestr = [weakSelf nowtime];
        weakSelf.logId = [NSString stringWithFormat:@"%@",model.logId];
        weakSelf.title = model.name;
        weakSelf.key =nil;
        weakSelf.searchController.active = NO;
        weakSelf.searchController.searchBar.text = @"";
        
        [weakSelf getNewList];

    };
}



- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.searchController.active = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}



#pragma mark 网络请求

- (void)getNewList {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    if (_logId.length > 0) {
        [params setObject:_logId forKey:@"logId"];
    }
    if (_searchKey.length > 0) {
        [params setObject:_searchKey forKey:@"key"];
    }
    [SVProgressHUD show];
    [params setObject:@(20) forKey:@"rows"];
    
    [_dateList removeAllObjects];
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPOrdorProcessList) params:params success:^(id object) {
        [self.dateList addObjectsFromArray:[NewOrdorListModel mj_objectArrayWithKeyValuesArray:object[@"body"][@"list"]]];
        self.title = [NSString stringWithFormat:@"%@", object[@"body"][@"title"]];
        [SVProgressHUD dismiss];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        [self.tableView reloadData];
        NSDictionary *dic = error.userInfo;
        NSString *msg = [dic objectForKey:@"msg"];
        [SVProgressHUD showErrorWithStatus:msg];
        [self.tableView.mj_header endRefreshing];
    }];

}

- (void)getMoreList {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    if (_logId.length > 0) {
        [params setObject:_logId forKey:@"logId"];
    }
    if (_key.length > 0) {
        [params setObject:_key forKey:@"key"];
    }
    if (_dateList.count > 0) {
        [params setObject:_dateList.lastObject.tradeOrderNum forKey:@"tradeOrderNum"];
    }else {
        [self.tableView.mj_footer endRefreshing];
        return;
    }
    [params setObject:@20 forKey:@"rows"];
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPOrdorProcessList) params:params success:^(id object) {
        [self.dateList addObjectsFromArray:[NewOrdorListModel mj_objectArrayWithKeyValuesArray:object[@"body"][@"list"]]];
        
        [self.tableView reloadData];
        
        [SVProgressHUD dismiss];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSError *error) {
        NSDictionary *dic = error.userInfo;
        NSString *msg = [dic objectForKey:@"msg"];
        [SVProgressHUD showErrorWithStatus:msg];
        [self.tableView.mj_footer endRefreshing];
    }];
}



#pragma mark tableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dateList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewOrdorListCell *cell = [tableView dequeueReusableCellWithIdentifier:newOrdorListCellIdentify forIndexPath:indexPath];
    if (indexPath.row == _dateList.count - 1) {
        cell.buttomView.constant = 0;
    }else {
        cell.buttomView.constant = 10;
    }
    [cell layoutIfNeeded];
    cell.delegate = self;
    cell.model = _dateList[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 181;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NewOrderDetailViewController *ctrl = [[UIStoryboard storyboardWithName:@"ZPaiyingxiao" bundle:[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"]] instantiateViewControllerWithIdentifier:@"NewOrderDetailViewController"];
    ZSBStatusInfo *statusInfo = [[ZSBStatusInfo alloc] init];
    statusInfo.tradeOrderNum = _dateList[indexPath.row].tradeOrderNum;
    ctrl.statusInfo = statusInfo;
    [self.navigationController pushViewController:ctrl animated:YES];
}

#pragma mark cellDelegate 

- (void)NewOrdorListCell:(NewOrdorListCell *)cell model:(NewOrdorListModel *)model ActionType:(NSInteger)type {
    
    
    if (type == 1) {
        
        NSInteger enterType = [[NSUserDefaults standardUserDefaults] integerForKey:@"NEWLOVEMARKETINGENTERTYPE"];
        if (enterType == 0) {
            
            NewMissonListDetailController *ctrl = [[UIStoryboard storyboardWithName:@"ZPaiyingxiao" bundle:[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"]] instantiateViewControllerWithIdentifier:@"NewMissonListDetailController"];
            ctrl.ordorId = model.orderId;
            ctrl.isOrdorListEnter = YES;
            [self.navigationController pushViewController:ctrl animated:YES];
            
        }else if (enterType == 1 || enterType == 2) {
            

            ISeeUserInfoModel *userInfo = [ISeeUserInfoModel mj_objectWithKeyValues:[[[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserInfo] mj_JSONObject]];
            
            NewMarketWebViewController *detail = [[NewMarketWebViewController alloc] init];
            detail.loadUrl = [NSString stringWithFormat:@"%@hmarket/#/workorder-detail?orderId=%@&session=%@&userId=%@",NMarketMainUrl, model.orderId, [[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserSession], userInfo.userId];

            [self.navigationController pushViewController:detail animated:YES];
        }
        
    }else if (type == 2) {
        
        
        NewOrdorListDetailViewController *ctrl = [[UIStoryboard storyboardWithName:@"ZPaiyingxiao" bundle:[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"]] instantiateViewControllerWithIdentifier:@"NewOrdorListDetailViewController"];
        NSMutableArray *array = [model.content mj_JSONObject];
        ctrl.dataList = array;
        [self.navigationController pushViewController:ctrl animated:YES];

    }
    
}


#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    _searchKey = searchController.searchBar.text;
    [self getNewList];
}


#pragma mark buttonAction 

-(void)rightBarButtonAction:(UIBarButtonItem *)btn{
    [_muneView show];
}


//获取当前时间
- (NSString *)nowtime{
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];
    NSString *datetime = [formatter stringFromDate:date];
    
    return datetime;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
